package com.pl.lc.user.listener;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.pl.lc.common.config.RabbitKeyConfig;
import com.pl.lc.common.param.GrowthAdd;
import com.pl.lc.common.param.MqMsg;
import com.pl.lc.user.entity.GrowthLog;
import com.pl.lc.user.entity.Level;
import com.pl.lc.user.mapper.GrowthLogMapper;
import com.pl.lc.user.mapper.LevelMapper;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.List;

/**
 * @version 1.0
 * @Author 小胤
 * @Date 2024/6/10 14:11
 * @注释
 */
@Component
public class GrowthRabbitListener {

    @Autowired
    private LevelMapper levelMapper;


    @Autowired
    private GrowthLogMapper growthLogMapper;

    @RabbitListener(queues = RabbitKeyConfig.Q_USER_GROWTH)
    public void growthListener(MqMsg msg){

        System.out.println("msg = " + msg);

        if (msg.getType() ==5){ // 积分成长值 消息

            // 得到需要增加的 积分
            GrowthAdd growthAdd = (GrowthAdd) msg.getMsg();

            // 1.根据uid 查询该用户积分  没有则直接插入积分  有增加积分
            QueryWrapper<Level> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("user_id",growthAdd.getUid());

            List<Level> levelList = levelMapper.selectList(queryWrapper);

            Level level = null;
            if (levelList==null || levelList.size() ==0){// 没有积分直接插入

                level  = new Level();

                level.setLevel(1);
                level.setGrowths(growthAdd.getGrowth());
                level.setName("练气");
                level.setUserId(growthAdd.getUid());
                level.setCtime(new Date());

                levelMapper.insert(level);

            }
            else {  // 积分存在
                level = levelList.get(0);

                // 积分增加
                level.setGrowths(level.getGrowths() +  growthAdd.getGrowth());

                // 等级是否改变
                if (level.getGrowths()<1000){
                    level.setLevel(1);
                    level.setName("练气");
                }
                else if (level.getGrowths()<10000){
                    level.setLevel(2);
                    level.setName("筑基");
                }
                else if (level.getGrowths()<100000){
                    level.setLevel(3);
                    level.setName("金丹");
                }


                levelMapper.updateById(level);

            }

            // 2记录日志
            GrowthLog growthLog = new GrowthLog();

            growthLog.setUserId(growthAdd.getUid())
                    .setType(growthAdd.getType())
                    .setInfo(growthAdd.getType()+"积分增加"+growthAdd.getGrowth())
                    .setCtime(new Date());

            growthLogMapper.insert(growthLog);

        }


    }

}
